import path from 'node:path';
import { TEMP_DIR } from '@/server/utils/constants';
import { formidable } from 'formidable';
import fse from 'fs-extra';
import { defineEventHandler } from 'h3';

export default defineEventHandler(async (event) => {
  const req = event.node.req;

  const form = formidable({});

  try {
    const [fields, files] = await form.parse(req);

    const [file] = files.file!;
    const [hash] = fields.hash!;
    const [fileHash] = fields.fileHash!;
    const [filename] = fields.filename!;

    const chunkDir = path.resolve(TEMP_DIR, `chunkDir_${filename}`);

    if (!fse.existsSync(chunkDir)) {
      fse.mkdirpSync(chunkDir);
    }

    fse.moveSync(
      file.filepath,
      path.resolve(chunkDir, `${fileHash}-${hash.split('-')[1]}`),
    );

    return { errno: 0, msg: `chunk ${hash} upload success` };
  } catch (e) {
    console.error(e);

    return { errno: -1, msg: 'upload fail' };
  }
});
